package com.imau.controller;

import com.alibaba.fastjson.JSON;
import com.imau.common.BaseException;
import com.imau.common.CommonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/handlerExcption")
public class HandlerExcptionServlet extends HttpServlet
{

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //响应设置统一编码
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

        //获取异常对象
        Throwable ex = (Throwable)request.getAttribute("javax.servlet.error.exception");


        // 判断:错误 还是 运行异常
        CommonResult result;
        if(ex.getClass() == BaseException.class) //Exception 级别
        {
            BaseException be = (BaseException)ex;

            result =  new CommonResult(be.getResultCode());

            System.out.println(result);

        }else {  //Error


             result =  CommonResult.FAIL();
            System.out.println(result);
        }

        response.getWriter().write(JSON.toJSONString(result));

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}

